package com.dailyblue.java.project.bookstore.interceptor;

import com.dailyblue.java.project.bookstore.exception.NotLoginException;
import com.dailyblue.java.project.bookstore.util.JwtConfig;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class IsLoginInterceptor implements HandlerInterceptor {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("开始校验用户是否登陆！");
        boolean flag = JwtConfig.checkToken(request);
        log.info("flag:{}", flag);
        if (!flag) {
            throw new NotLoginException("用户未登录！");
        }
        String requestToken = request.getHeader("token");
        log.info("requestToken:{}", requestToken);
        Claims claims = JwtConfig.parseJWT(requestToken);
        log.info("claims:{}", claims);
        log.info("id:{}", claims.get("id"));
        ValueOperations<String, String> values = stringRedisTemplate.opsForValue();
        String redisToken = values.get("token:" + claims.get("id"));
        String token = request.getHeader("token");
        log.info("redis:{},request:{}", redisToken, token);
        if (redisToken == null || !redisToken.equals(token)) {
            throw new NotLoginException("用户未登录！");
        }
        log.info("用户已经登陆");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
